package com.mxl.mvc.cashorder;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.mxl.common.BeanConvertUtil;
import com.mxl.common.SelectOptionUtil;
import com.mxl.common.StringUtil;
import com.mxl.common.helper.OrderStatus;
import com.mxl.common.helper.ResponseErrorCode;
import com.mxl.common.rule.RuleEngine;
import com.mxl.dao.cashorder.GatewayRequestDao;
import com.mxl.dao.cashorder.impl.CardRuleDaoImpl;
import com.mxl.dao.cashorder.impl.GatewayPayRequestDaoImpl;
import com.mxl.dao.cashorder.impl.PurchaseOrderDaoImpl;
import com.mxl.dao.cashorder.model.CardRule;
import com.mxl.dao.cashorder.model.GatewayPayOrder;
import com.mxl.dao.cashorder.model.GatewayPayRequest;
import com.mxl.dao.cashorder.model.GatewayRequest;
import com.mxl.dao.cashorder.model.PurchaseOrder;
import com.mxl.service.cashorder.GatewayPayOrderService;
import com.mxl.service.cashorder.dto.CashOrderRequest;

/**
 * 卡支付页面
 * 
 * @author xianglin.mo
 * 
 */
public class GatewayCardPayController extends MultiActionController {

	private GatewayRequestDao gatewayRequestDao;

	private GatewayPayRequestDaoImpl gatewayPayRequestDao;

	private RuleEngine gatewayPayRequestEngine;

	private String errorView;

	private PurchaseOrderDaoImpl purchaseOrderDao;

	private CardRuleDaoImpl cardRuleDao;

	private GatewayPayOrderService gatewayPayOrderService;

	@SuppressWarnings("unchecked")
	public ModelAndView index(final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {
		// 从标准网关页面 获取参数 卡密 卡号 等信息 订单id
		request.setCharacterEncoding("UTF-8");
		// 判断验证码
		String randCode = request.getParameter("randCode");
		WebApplicationContext rc = WebApplicationContextUtils
				.getWebApplicationContext(request.getSession()
						.getServletContext());
		if (StringUtil.isEmpty(randCode)
				|| !randCode.trim().equalsIgnoreCase(
						request.getSession().getAttribute("rand").toString())) {
			// 输出界面提示.
			responseReturnContent(
					response,
					new StringBuilder().append(
							rc.getMessage(ResponseErrorCode.RANK_CODE_ERROE
									.getValue(), null, Locale.CHINESE))
							.toString());
			return null;
		}
		// 保存请求
		CashOrderRequest req = wrapRequest(request);

		GatewayPayRequest reqpay = (GatewayPayRequest) BeanConvertUtil
				.convert(GatewayPayRequest.class, req,
						new String[] { "customMerchant" });
		gatewayPayRequestDao.save(reqpay);
		// 针对接口参数一一校验
		// 还需要判断卡号卡密和表中是否一致
		try {
			gatewayPayRequestEngine.processRequest(req);
		} catch (Exception e) {
			req.setMsgId(ResponseErrorCode.FAIL.getValue());
			logger.error(
					"GatewayCardPayController gatewayPayRequestEngine fail----membercode orderId:"
							+ req.getOrderId(), e);

		}
		// 反馈等待页面 处理进行中的页面 然后一个定时去查询结果 最后展现给用户
		req.setMsgId(StringUtil.isEmpty(req.getMsgId()) ? ResponseErrorCode.SUCC
				.getValue() : req.getMsgId());
		responseReturnContent(
				response,
				new StringBuilder().append(req.getMsgId()).append(";")
						.append(req.getSeqId()).toString());
		return null;
	}

	@SuppressWarnings("unchecked")
	public ModelAndView check(final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {
		// 从标准网关页面 获取参数 卡密 卡号 等信息 订单id
		request.setCharacterEncoding("UTF-8");
		// 保存请求
		CardRule rule = cardRuleDao.getBosstype(request.getParameter("cardNo")
				.trim().length(), request.getParameter("cardPwd").trim()
				.length());
		// 根据错误码去获取 错误码信息
		WebApplicationContext rc = WebApplicationContextUtils
				.getWebApplicationContext(request.getSession()
						.getServletContext());
		if (rule == null) {
			responseReturnContent(
					response,
					new StringBuilder()
							.append(ResponseErrorCode.CARD_NOT_SUPPER
									.getValue())
							.append("@")
							.append(rc.getMessage(
									ResponseErrorCode.CARD_NOT_SUPPER
											.getValue(), null, Locale.CHINESE))
							.toString());
			return null;
		}
		// 暂时获取默认的卡支持金额 后续有商户定制 则从商户表中获取
		String orderAmount = request.getParameter("orderAmount").trim();
		orderAmount = orderAmount.replace(",", "");
		String amount = SelectOptionUtil.setAmountList(rule.getCardAmount(),
				Long.valueOf(orderAmount));
		responseReturnContent(
				response,
				new StringBuilder()
						.append(ResponseErrorCode.SUCC.getValue())
						.append("@")
						.append(rule.getBossType())
						.append("@")
						.append(rule.getCardType())
						.append("@")
						.append(rule.getCardRegion() == null ? "" : rule
								.getCardRegion()).append("@").append(amount)
						.toString());
		// 反馈等待页面 处理进行中的页面 然后一个定时去查询结果 最后展现给用户
		return null;
	}

	@SuppressWarnings("unchecked")
	public ModelAndView queryStatus(final HttpServletRequest request,
			final HttpServletResponse response) throws Exception {
		// 从网关订单号 721
		request.setCharacterEncoding("UTF-8");
		// 查询订单是否成功
		String seqId = request.getParameter("seqId");
		GatewayPayOrder gpo = gatewayPayOrderService.queryBuSeqId(seqId);
		// 判断是否超时--统一跳转到一个页面 然后在跳转到商户页面
		// String status = ResponseErrorCode.ORDER_ING.getValue();
		String responseUrl = "";
		if (gpo.getOrderStatus() == OrderStatus.FAIL.getValue()
				|| gpo.getOrderStatus() == OrderStatus.SUCC.getValue()) {
			// status = ResponseErrorCode.SUCC.getValue();
			WebApplicationContext rc = WebApplicationContextUtils
					.getWebApplicationContext(request.getSession()
							.getServletContext());
			responseUrl = getNotifyRul(gpo,
					rc.getMessage(gpo.getErrorCode(), null, Locale.CHINESE));
		} else if (timeout(gpo.getCreationDate())) {
			// status = ResponseErrorCode.SUCC.getValue();
			responseUrl = "testencode.htm?method=back";
		}
		// 根据错误码去获取 错误码信息
		responseReturnContent(response, responseUrl);
		// 反馈等待页面 处理进行中的页面 然后一个定时去查询结果 最后展现给用户
		return null;
	}

	private String getNotifyRul(GatewayPayOrder gorder, String msg) {
		// 加签原串
		PurchaseOrder p = purchaseOrderDao.get(Long.valueOf(gorder.getPid()));
		// String signO = MessageFormat
		// .format("version=1.00member_code={0}order_time={1}order_id={2}order_amount={3}amount={4}seq_id ={5}card_no={6}card_pwd={7}ret_code={8}merchant_key={9}",
		// gorder.getMemberCode(), "", gorder.getOrderId(),
		// gorder.getOrderAmount(), gorder.getAllowAmount(),
		// gorder.getSeqId(), p.getCardNo(), p.getCardPwd(),
		// gorder.getErrorCode(), key);
		// logger.debug("notify member berfor signO:" + signO);
		// String md5Sign = new String(MD5Util.md5Hex(signO).toLowerCase());
		String url = MessageFormat
				.format("version=1.00&member_code={0}&order_time={1}&order_id={2}&order_amount={3}&amount={4}&seq_id ={5}&card_no={6}&card_pwd={7}&ret_code={8}&ret_msg={9}&bossType={10}",
						gorder.getMemberCode(), "", gorder.getOrderId(),
						String.valueOf(gorder.getOrderAmount()),
						String.valueOf(gorder.getAllowAmount()),
						gorder.getSeqId(), p.getCardNo(), p.getCardPwd(),
						gorder.getErrorCode(), msg, p.getBossType());
		StringBuffer res = new StringBuffer();
		res.append(gorder.getRedirectUrl()).append("?").append(url);
		logger.info("******page notify member RedirectUrl:" + res);
		return res.toString();
	}

	// 大于90秒超时
	private boolean timeout(Date date) {
		return (System.currentTimeMillis() - date.getTime()) > 90000;
	}

	/**
	 * 直接返回内容.
	 * 
	 * @param response
	 * @param content
	 */
	private void responseReturnContent(HttpServletResponse response,
			String content) {
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.write(content);
			writer.flush();
		} catch (IOException e) {
			logger.error("responseReturnContent error", e);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	private CashOrderRequest wrapRequest(final HttpServletRequest request) {
		String id = request.getParameter("requestId");
		GatewayRequest req = gatewayRequestDao
				.findById(Long.valueOf(id.trim()));
		CashOrderRequest gatewayRequestDTO = (CashOrderRequest) BeanConvertUtil
				.convert(CashOrderRequest.class, req,
						new String[] { "customMerchant" });
		gatewayRequestDTO.setCardNo(request.getParameter("cardNo").trim());
		gatewayRequestDTO.setBossType(Integer.valueOf(request.getParameter(
				"bossType").trim()));
		gatewayRequestDTO.setCardPwd(request.getParameter("cardPwd").trim());
		gatewayRequestDTO.setSelectAmount(Long.valueOf(request.getParameter(
				"selectAmount").trim()));
		gatewayRequestDTO
				.setMobileNo(request.getParameter("mobileNo") == null ? ""
						: request.getParameter("mobileNo").trim());
		gatewayRequestDTO.setRequestId(req.getId());
		return gatewayRequestDTO;
	}

	public void setErrorView(String errorView) {
		this.errorView = errorView;
	}

	public void setGatewayRequestDao(GatewayRequestDao gatewayRequestDao) {
		this.gatewayRequestDao = gatewayRequestDao;
	}

	public void setGatewayPayRequestDao(
			GatewayPayRequestDaoImpl gatewayPayRequestDao) {
		this.gatewayPayRequestDao = gatewayPayRequestDao;
	}

	public void setGatewayPayRequestEngine(RuleEngine gatewayPayRequestEngine) {
		this.gatewayPayRequestEngine = gatewayPayRequestEngine;
	}

	public void setCardRuleDao(CardRuleDaoImpl cardRuleDao) {
		this.cardRuleDao = cardRuleDao;
	}

	public void setGatewayPayOrderService(
			GatewayPayOrderService gatewayPayOrderService) {
		this.gatewayPayOrderService = gatewayPayOrderService;
	}

	public void setPurchaseOrderDao(PurchaseOrderDaoImpl purchaseOrderDao) {
		this.purchaseOrderDao = purchaseOrderDao;
	}

}
